<template>
  <div class="chart" ref="chartRef"></div>
</template>

<script setup>
import { ref, onMounted, watch, onUnmounted } from 'vue';
import * as echarts from 'echarts';

const props = defineProps({
  chartData: {
    type: Array,
    required: true
  },
  theme: {
    type: String,
    default: 'light'
  }
});

const chartRef = ref(null);
let chart = null;

function initChart() {
  if (!chartRef.value) return;
  
  // 销毁旧图表
  if (chart) {
    chart.dispose();
  }
  
  // 根据主题初始化
  chart = echarts.init(chartRef.value, props.theme);
  
  // 根据主题设置不同配色
  const colors = props.theme === 'dark' 
    ? ['#177ddc', '#49aa19', '#d89614', '#a61d24'] 
    : ['#1890ff', '#52c41a', '#fa8c16', '#f5222d'];
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center',
      data: props.chartData.map(item => item.name)
    },
    series: [
      {
        name: '工单状态',
        type: 'pie',
        radius: ['50%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: props.theme === 'dark' ? '#141414' : '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '16',
            fontWeight: 'bold'
          },
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        labelLine: {
          show: false
        },
        data: props.chartData,
        color: colors,
        animationType: 'scale',
        animationEasing: 'elasticOut',
        animationDelay: function (idx) {
          return Math.random() * 200;
        }
      }
    ]
  };
  
  chart.setOption(option);
}

function resizeChart() {
  chart && chart.resize();
}

// 监听主题变化
watch(() => props.theme, () => {
  initChart();
});

// 监听数据变化
watch(() => props.chartData, () => {
  initChart();
}, { deep: true });

onMounted(() => {
  initChart();
  window.addEventListener('resize', resizeChart);
});

onUnmounted(() => {
  chart && chart.dispose();
  window.removeEventListener('resize', resizeChart);
});
</script>

<style scoped>
.chart {
  width: 100%;
  height: 100%;
}
</style> 